package my2Cents.tools;

import java.awt.Color;
import java.io.Serializable;

import my2Cents.Sandbox;
import my2Cents.Spawner;
import my2Cents.Undo;
import my2Cents.properties.CheckBox;
import my2Cents.properties.KeyAssign;
import my2Cents.properties.Property;
import my2Cents.properties.Slider;
import net.phys2d.raw.Body;
import net.phys2d.raw.StaticBody;

public class SpawnerTool extends AbstractBodyModifier implements Serializable {
	private int spawnKey = -1;
	private int timer = -1;
	private boolean createStatic = true;
	
	public SpawnerTool() {
		setName("Spawner Tool");
		setDescription("Turns an object into a spawner.\n" +
					   "Assign the spawn key.");
		
		KeyAssign spawnKeyAssign = new KeyAssign("Spawn") {
			public void valueChanged(int value, char ch) {
				spawnKey = value;
			}
		};
		addProperty(spawnKeyAssign);
		
		Property p = new Slider("Spawned LifeSpan",0,0,60,10,true) {
			public void valueChanged(int value) {
				timer = value;
			}
		};
		this.addProperty(p);
		
		addProperty(new CheckBox("Static (Frozen)",createStatic) {
			private static final long serialVersionUID = 1L;
			public void valueChanged(boolean b) {
				createStatic = b;
			}
		});
	}
	
	private void setupSpawner(Spawner s) {
		s.setSpawnCode(spawnKey);
		s.setBodyLifeSpan(timer);
		s.setStatic(createStatic);
		s.doOutlineFx();
	}
	
	protected void modify(Body b) {
		if(b instanceof Spawner) {
			setupSpawner((Spawner) b);
			return;
		}
		if(b.isStatic()) {
			Sandbox.Msg("Body must be non-static.", "error.jpg");
			return;
		}
		Spawner spawner = new Spawner(b);
		setupSpawner(spawner);
		Sandbox.getWorld().add(spawner);
		Sandbox.getWorld().remove(b);
		
		final Body bod = b;
		Undo toolUndo = new Undo(spawner, getWorld(), getName()) {
			/**
			 * 
			 */
			private static final long serialVersionUID = 8597192651281971255L;

			public void performUndo() {
				Spawner spawner = (Spawner) this.getObject();
				
				bod.setPosition(spawner.getPosition().getX(),
								spawner.getPosition().getY());
				bod.setRotation(spawner.getRotation());
				
				//Sandbox.getWorld().add(bod);
				Sandbox.getWorld().remove(spawner);
			}
		};
		Sandbox.getUndoList().add(toolUndo);
	}
	
	protected void unModify(Body b) {
		b.setRemoveOther(false);
		b.setDrawColor(Color.BLACK);
	}
}
